package com.richfit.barcodesystem_cczt.scanservice;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.richfit.barcodesystem_cczt.activitis.base.BaseActivity;
import com.richfit.barcodesystem_cczt.utils.toast.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public abstract class BaseBarScannerActivity extends BaseActivity {

    IScanService scanService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initVariables();
    }

    public void initVariables() {
        //初始化扫描服务
        scanService = ScanServiceFactory.getScanService();
        scanService.initScanService(this);
        //注册EventBus
        EventBus.getDefault().register(this);
    }

    /**
     * 开启扫描服务
     */
    @Override
    public void onResume() {
        super.onResume();
        scanService.openScanService();
    }

    /**
     * 关闭扫描服务
     */
    @Override
    protected void onPause() {
        scanService.closeScanService();
        super.onPause();
    }

    /**
     * 销毁扫描服务和EventBus
     */
    @Override
    public void onDestroy() {
        scanService.destroyScanService();
        scanService = null;
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_F5:
                scanService.startScan();
                break;
            case KeyEvent.KEYCODE_F4:
                scanService.startScan();
                break;
            case KeyEvent.KEYCODE_1:
                scanService.startScan();
                break;
            case KeyEvent.KEYCODE_FUNCTION:
                scanService.startScan();
                break;
            case KeyEvent.KEYCODE_STEM_2:
                scanService.startScan();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 对扫描结果进行解密
     *
     * @param barCodeData
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void decodeScanResult(BarCodeData barCodeData) {
        String info = barCodeData.getData();
        if (TextUtils.isEmpty(info)) {
            return;
        }
        Log.e("yff", "扫描条码的原始内容 = " + info);
        //仓位和单据不加密
        int length = info.split("\\|", -1).length;
        String barcodeInfo;
        if (length <= 2) {
            barcodeInfo = info;
        } else {
            barcodeInfo = ScanUtil.CharTrans(info);
        }

        if (TextUtils.isEmpty(barcodeInfo)) {
//            showMessage("单据条码信息为空");
            ToastUtil.showTextShort("单据条码信息为空");

            return;
        }
        Log.d("yff", "解码之后的条码内容" + barcodeInfo);
        String[] a = barcodeInfo.split("\\|", -1);
        handleBarCodeScanResult("", a);
    }
}